$(function(){
	var str="";
	$.ajax({
	url:contextPath + "/matchIcd/operDicType.dhc",
		data:{"icdType":"O"},
		dataType:"json",
		type:'post',
		async:false,
		success:function(data){
			if(data.length>0){
				for(var i in data){
					str += '<option value="'+data[i].DIC_VALUE+'">'+data[i].DIC_DESC+'</option>';
				}
				$("#"+tabId+" #icdVersion").html(str);
			}
		}
	});
	 
	//文件上传
	$("#"+tabId+" #import_icdOper_file").uploadifive({
		'uploadScript' : contextPath + '/matchIcd/fileUploadICDOper.dhc',
        'height': 31 ,
        'width' :120 ,
        'auto'  : true ,//是否自动开始
        'uploadLimit' : 100, //一次同步上传的文件数目     
        'fileSizeLimit' : '500MB', //单个文件大小，0为无限制，可接受KB,MB,GB等单位的字符串值     
        'queueSizeLimit' : 100, //队列中同时存在的文件个数限制
        'fileObjName':'file',
        'removeCompleted': true ,  //是否完成后移除序列，默认为true
        'removeTimeout' : '5',  //上传完成后队列多长时间后消失。默认 3秒    需要：removeCompleted : true,时使用
        'progressData' :'percentage',//设置上传进度显示方式，percentage显示上传百分比，speed显示上传速度
        'buttonText' : '<i class="fa fa-folder-open fa-lg"></i>&nbsp;&nbsp;选择导入文件',
        'buttonClass': 'uploadifyH5_blue_btn',
        'fileType' : '*.xls; *.xlsx; *.xml; *.dbf',//允许上传的文件格式
        'multi'    : true,//是否支持多文件上传
        'method'   :'post',//提交方式
        'debug':false,
        //当点击文件队列中文件的关闭按钮或点击取消上传时触发
        'onCancel': function(){},
      	//返回一个错误，选择文件的时候触发  
        'onSelectError':  function(){
        	drgUI.error("文件上传失败！") ;
        },
      	//检测FLASH失败调用  
        'onFallback':function(){  
            drgUI.error("浏览器检测不到兼容版本的HTML5。 ") ;
        }, 
        'onUploadError' : uploadify_onUploadError,
        'onQueueComplete':function(res){
        	ICDMATCH.showProgress("oper");//获取进度
			   $.ajax({
		       		 url :contextPath+'/matchIcd/analysisICDOper.dhc',
		       		 data : {
		       			 "icdVersion": $("#"+tabId+" #icdVersion").val(),
		       			 "icdType":"O"
		       		 },
		       		 type:'post',
		       		 async:true,
		       		 dataType : "json",//这里的dataType就是返回回来的数据格式了html,xml,json
		       		 cache: false,//设置是否缓存，默认设置成为true，当需要每次刷新都需要执行数据库操作的话，需要设置成为false
		       		 success : function(result) {	 
			       			if(!result.success){
			       				drgUI.warning("请检测数据文件准确性");
				       		}else{
				       			drgUI.success("导入成功！");
				       			getResult("");
				       		}
			       		 }
		       	 });
		}
	}); 
	// 上传按钮 悬浮小手
	$("[type=file]").css({"cursor":"pointer"});
	$("#"+tabId+" #updateButton").click(function(){
		ICDOperDialog();
	})
	
	/*
	 * 更新按钮的弹出框
	 */
	function ICDOperDialog(){
			$.post(contextPath + '/pages/icdMatch/top-dialog.jsp').done(function(dialogdata) {
				var dialog = $(dialogdata);
				dialog.find(".modal-title").html(" 增加或更新ICD手术对照 ");//顶部标题
				dialog.find(".modal-dialog").css("width","40%");//弹出框宽度	
				dialog.find(".modal-body").css("min-height","260px");//高度	
				dialog.modal({
							keyboard : false
						}).on({ 'hidden.bs.modal' : function() {
							$(this).remove();
							},
						'shown.bs.modal' : function() {
						dialog.find(".modal-body").empty();
						var str = '';
						str+='<div class="container-fluid">';
						str+='<div class="row" style="height:30px;margin-top:20px;">';
						str+='<div class="col-xs-4"  >';
						str+='<label class="control-label" style="text-align:right;float:right;line-height:30px;width:100%">医院手术ICD编码:</label>';
						str+='</div>';
						str+='<div class="col-xs-6"">';
						str+='<input id="hospICDOperCode" type="text" class="form-control" placeholder="请输入本院手术编码" onblur="findOperDescByCode()"  >  ';
						str+='</div>';
						str+='</div>';
						str+='<div class="row" style="height:30px;clear:both;margin-top:15px">';
						str+='<div class="col-xs-4"  >';
						str+='<label class="control-label" style="text-align:right;float:right;line-height:30px;width:100%">医院手术ICD描述:</label>';
						str+='</div>';
						str+='<div class="col-xs-6"">';
						str+='<select  id="hospICDOperDesc"  class="form-control select " placeholder="" ></select> ';
						str+='</div>';
						str+='</div>';
						str+='<div class="row" style="height:30px;clear:both;margin-top:15px">';
						str+='<div class="col-xs-4"  >';
						str+='<label class="control-label" style="text-align:right;float:right;line-height:30px;width:100%">北京手术ICD编码:</label>';
						str+='</div>';
						str+='<div class="col-xs-6"">';
						str+='<input id="BJICDOperCode" type="text" class="form-control"  placeholder="请输入北京手术编码" onblur="findBJOperDescByCode()">  ';
						str+='</div>';
						str+='</div>';
						str+='<div class="row" style="height:30px;clear:both;margin-top:15px">';
						str+='<div class="col-xs-4"  >';
						str+='<label class="control-label" style="text-align:right;float:right;line-height:30px;width:100%">北京手术ICD描述:</label>';
						str+='</div>';
						str+='<div class="col-xs-6"">';
						str+='<input id="BJICDOperDesc" type="text" class="form-control" placeholder="" >  ';
						str+='</div>';
						str+='</div>';
						str+='</div> </div>'
						dialog.find(".modal-body").append(str);//向弹出框添加
						var footStr = '';
						footStr+='<div style="text-align:right">';
						footStr+='<button id="operCancle" class="btn btn-primary" data-dismiss="modal">取消</button>';
						footStr+='<button id="operSave" class="btn btn-primary" data-dismiss="modal">保存</button>';
						footStr+='</div>';
						dialog.find(".modal-footer").append(footStr);
						
						/**
						 * 把更新的内容传入到后端
						 */
						dialog.find('#operSave').on('click',function(){
							var icdVersion = $("#"+tabId+" #icdVersion").val();
							var hICDCode = dialog.find('#hospICDOperCode').val();
							var hICDDesc = dialog.find('#hospICDOperDesc').val();
							var newBJICDCode = dialog.find('#BJICDOperCode').val();
							var newBJICDDesc = dialog.find('#BJICDOperDesc').val();
							$.ajax({
								url : contextPath + '/matchIcd/updateOneICD.dhc',
								data : {
									"icdType":"O",
									"icdVersion":icdVersion,
									"hICDCode":hICDCode,
									"hICDDesc":hICDDesc,
									"bjICDCode":newBJICDCode,
									"bjICDDesc":newBJICDDesc
								},
								type : 'post',
								async : true,
								dataType : "json",// 这里的dataType就是返回回来的数据格式了html,xml,json
								cache : false,// 设置是否缓存，默认设置成为true，当需要每次刷新都需要执行数据库操作的话，需要设置成为false
								success : function(result) {
									if(!result.success){
											drgUI.error(result.errorMessage) ;
						    			}
									else{
										drgUI.success("更新成功") ;
									}
								}
							});
						});
						
						}
					});
				});
	}	
	$("#"+tabId+" #matchButton").click(function(){  
		$('#'+tabId+' #self_icdmatch_id').fadeIn(0);
		$.ajax({
			url: contextPath+"/matchIcd/matchICD.dhc",
			data: {icdVersion: $("#"+tabId+" #icdVersion").val(), icdType:"O"},
			dataType: "json",
			success: function(data){
				if(data.success){
					drgUI.success("对照完毕") ;
					var depCode = $("#"+tabId+" #depSelector").combobox('getValue');
					getResult(depCode);
				}else{
					drgUI.error(data.errorMessage) ;
				}
				$('#'+tabId+' #self_icdmatch_id').fadeOut(0);
			}
		})
	})
	
	$("#"+tabId+" #icdVersion").change(function(o, n){
		var depCode = $("#"+tabId+" #depSelector").combobox('getValue');
	    getResult(depCode);
	})
	
	$.post(contextPath + "/Department/findAllDepartment.dhc").done(function(data){
		var deps = data.data;
		deps = [{depCode: "", depName: "全部"}].concat(deps);
		$CommonUI.combobox($("#"+tabId+" #depSelector"),deps,"depName","depCode",{
			"height" : 28,//设定框的高度
			"onSelect" : function(com) {
				getResult(com.depCode);
			}
		});
	});
	getResult("");
	/**
	 * 对照结果信息统计
	 */
	function getResult(depCode){
		getICDMatchResult("O", depCode);	
		getICDMatch("O", "0", depCode);	
		getICDMatch("O", "1", depCode)	
		getICDMatch("O", "2", depCode);	
		getICDMatch("O", "3", depCode);		
		getICDMatch("O", "4", depCode);
	}
	
	//获取匹配结果
	function getICDMatchResult(icdType, depCode){
		$.post(contextPath+"/matchIcd/getICDMatchResult.dhc", {icdType: icdType, icdVersion: $("#"+tabId+" #icdVersion").val(), depCode: depCode}).done(function(data){
			if(data.data){
				var markData = data.data.markData;
				var tableData = data.data.tableData;
				var str = '';
				str+=' <table class="table table-striped" style="width:100%"> ';
				str+=' 	<thead> ';
				str+=' 		<tr> ';
				str+=' 			<td>类型</td> ';
				str+=' 			<td>数量</td> ';
				str+=' 			<td>占比(%)</td> ';
				str+=' 		</tr> ';
				str+=' 	</thead> ';
				str+=' 	<tbody> ';
				str+=' 	</tbody> ';
				str+=' </table> ';
				//str+=' <div class="showDetil" style="display: block;"><div>注：</div><div>1.ICD-9-BM('+$("#"+tabId+" #icdVersion").val()+') 手术数共'+markData.bjICDs+'个，其中未匹配'+markData.notMatchICDs+'个，占'+markData.notMatchICDPercent+'%</div> ';
			//	str+=' <div>2.匹配数量不一定等于真实的ICD数量，因为同一个ICD可以生成多条匹配记录</div></div> ';
				$("#"+tabId+" #icd_match_result_d").find(".dataTables_wrapper").html(str);
				var columns=[ 
								{ "data": "ddesc"},
								{ "data": "value"},
								{ "data": "percent"}
	    	                 ];
				var paramsDataTables={searching:false,lengthChange:false,ordering:false,info:false};
				$("#"+tabId+" #icd_match_result_d").find(".dataTables_wrapper>table").dataTableBasic(columns,tableData,paramsDataTables);
				
				var pieData = [];
				for(var o in tableData){
					if(o==0) continue;
					var pie = {"name": tableData[o].ddesc, "value": tableData[o].value};
					pieData.push(pie);
				}
				var chartParams={radius:[0,'50%']};
				pieCharts($("#"+tabId+" #icd_match_result_d").find(".echartscq"), pieData, "", "",chartParams);
			}
		});
	}

	//获取ICD匹配结果
	function getICDMatch(icdType, matchType, depCode){
		var param = {icdType: icdType, matchType: matchType, icdVersion: $("#"+tabId+" #icdVersion").val(), depCode: depCode};
		$.post(contextPath+"/matchIcd/getICDMatching.dhc", {param: JSON.stringify(param)}).done(function(data){
			var str = '';
			str+=' <table class="table table-striped" style="width:100%"> ';
			str+=' 	<thead> ';
			str+=' 		<tr> ';
			str+=' 			<td>医院ICD编码及描述</td> ';
			str+=' 			<td>北京ICD编码及描述(单击可编辑)</td> ';
			str+=' 			<td>最后一次修改时间</td> ';
			str+=' 			<td>操作</td> ';
			str+=' 		</tr> ';
			str+=' 	</thead> ';
			str+=' 	<tbody> ';
			str+=' 	</tbody> ';
			str+=' </table> ';
			$("#"+tabId+" #icd-match-"+matchType+"-"+icdType).html(str);
			var columns=[ 
							{ "data": "hICDDesc_1",
								  "render": function(obj, type, full){
									  return ""+full.HICDCODE+"-"+full.HICDDESC;
								  }
								},
								{ "data": "bjICDDesc",
								  "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
									  $(nTd).addClass('inputTd');
									  $(nTd).attr('hICDCode', oData.HICDCODE);
									  $(nTd).attr('hICDDesc', oData.HICDDESC);
									  $(nTd).attr('bjICDCode', oData.BJICDCODE);
								   },
								   "render": function(obj, type, full){
									   var code=full.BJICDCODE==null?'-':full.BJICDCODE;
									   var desc=full.BJICDDESC==null?'-':full.BJICDDESC;
									   return ""+code+"-"+desc;
								   }
								},
								{ "data": "LASTUPDATEDATE"},
								{ "data": "OPERATION",
								  "render": function(obj, type, full){
									  var icdId = full.ICDID;
									  return "<a href=\"javascript:editLog('"+full.HICDCODE+"')\">日志</a>";
								  }
								}
	    	                 ];
			var paramsDataTables={info:false,stateSave:true,order:[[ 2, "desc" ]]};
			var drawCallback=function( oSettings ){
				$(this).find("tbody").off('click', 'td.inputTd');
				$(this).find("tbody").on('click', 'td.inputTd', function () {
					var nTd = $(this);
					nTd.removeAttr("class");
					var value = nTd.html();
					nTd.html("<input class='icd_select'><button class='ok'>确定</button><button class='cancel'>取消</button>");
					$CommonUI.combobox(nTd.find("input.icd_select"),"","bjICDDesc","bjICDCode",{
						loader: function(param, success){
							var q = param.q || "";
							$.post(contextPath + "/matchIcd/getBJICD.dhc", {icdType: icdType, icdVersion: $("#"+tabId+" #icdVersion").val(), icdValue: nTd.attr("hICDCode")+"-"+nTd.attr("hICDDesc"), icdValue1: q}).done(function(data){
								success(data);
							})
						},
						groupField:"group"
					});
					nTd.find("input.icd_select").combobox("setValue", nTd.attr("bjICDCode")).combobox("setText", value);
					nTd.find("button.ok").click(function(){
						var newCode = nTd.find("input").combobox("getValue");
						var newDesc = nTd.find("input").combobox("getText");
						nTd.html(value);
						nTd.attr("class", "inputTd");
						if(newDesc!=""){
							
							var param = {
								hICDCode: nTd.attr("hICDCode"),
								hICDDesc: nTd.attr("hICDDesc"),
								bjICDCodeOld: nTd.attr("bjICDCode"),
								bjICDCodeNew: newCode,
								bjICDDescNew: newDesc.replace(newCode, "").trim(),
								editType: "2",
								icdType:"O",
								icdVersion: $("#"+tabId+" #icdVersion").val()
							}
							$.post(contextPath + "/matchIcd/updateICDMatching.dhc", {param: JSON.stringify(param)}).done(function(data){
								if(data.success){
									getICDMatch(icdType, matchType);
									if(matchType != "1"){
										getICDMatch(icdType, "1");
									}
                                    getICDMatchResult("O", "");
								}
							})
						}
					});
					nTd.find("button.cancel").click(function(){
						nTd.html(value);
						nTd.attr("class", "inputTd");
					})
				});
			};
			paramsDataTables.drawCallback=drawCallback;
			if(matchType==3){
				paramsDataTables.buttons=[ {
	                text: '全部提交',
	                action: function ( e, dt, node, config ) {
	                	var button=this;
	            		drgUI.confirm({
	            			content : '确定要全部提交?',
	            			callSure : function() {
	            				var aoData=$("#"+tabId+" #icd-match-3-O").find("table").DataTable().columns().context[0].aoData;
	        	                if(aoData.length==0){
	        	                	 drgUI.warning("无待提交数据！");
	        	                	 return;
	        	                }
	            				$.post(contextPath + "/matchIcd/batchSummitIcd.dhc", {icdType:icdType, matchType:matchType, icdVersion:$("#"+tabId+" #icdVersion").val()}).done(function(data){
	            					if(data.success){
	            						getResult(depCode);
				            			drgUI.success("数据提交成功！");
	            					}else{
	            						drgUI.error(data.errorMessage);
	            					}
	            				});
	            			}
	            		}); 
	                }
	            }];
			}
			$("#"+tabId+" #icd-match-"+matchType+"-"+icdType).find("table").dataTableBasic(columns,data.data,paramsDataTables);
		})
	}
});

function editLog(hICDId){
	$.post(contextPath + "/pages/common/top-dialog.jsp").done(function(data){
		var dialog = $(data);
		dialog.find(".modal-title").html(hICDId+"ICD修改日志");
		$.post(contextPath + "/matchIcd/getEditLog.dhc", {hICDCode: hICDId, icdVersion:$("#"+tabId+" #icdVersion").val()}).done(function(data){
			var str = '';
			str+=' <table class="stripe cc table" id="editLog"  style="width:100%;"> ';
			str+=' 	<thead> ';
			str+=' 		<tr> ';
			str+=' 			<td>医院ICD编码ID</td> ';
			str+=' 			<td>修改时间</td> ';
			str+=' 			<td>操作人</td> ';
			str+=' 			<td>操作类型</td> ';
			str+=' 			<td>原ICD编码</td> ';
			str+=' 			<td>新ICD编码</td> ';
			str+=' 		</tr> ';
			str+=' 	</thead> ';
			str+=' 	<tbody> ';
			str+=' 	</tbody> ';
			str+=' </table> ';
			dialog.find(".echartscq").html(str);
			var columns=[ 
							{ "data": "HICDCODE"},
							{ "data": "EDITDATE"},
							{ "data": "USERCODE"},
							{ "data": "editType1",
							  "render": function(obj, type, full){
								  var type = full.EDITTYPE;
								  if(type=="1"){
									  return "新建"
								  }else if(type=="2"){
									  return "修改"
								  }else if(type=="3"){
									  return "录入"
								  }else{
									  return "其他"
								  }
							  }
							},
							{ "data": "OLDBJICDCODE"},
							{ "data": "NEWBJICDCODE"}
 	                 ];
			var paramsDataTables={lengthChange:false,ordering:false,info:false};
			dialog.find(".modal-body").html(str);//弹出框宽度	
			dialog.find("table").dataTableBasic(columns,data.data,paramsDataTables);
		})
		dialog.modal({
			keyboard: false
		}).on({
			'hidden.bs.modal' : function(){
				$(this).remove();
			},
			'shown.bs.modal' : function(){
				$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
			}
		});
	});
}
/**
 * @void
 * @ Discription:根据诊断编码获取描述
 * @icdMatch.js
 */
function findOperDescByCode(){
	var code=$('#hospICDOperCode').val();
	if(!code) return;
	$('#hospICDOperDesc').html();
	var str='<option value="none">请填写正确手术编码</option>';
	$.post(contextPath + "/matchIcd/findDescByCode.dhc",{"type":"O","code":code}).done(function(result){
		if(result.success && result.data.length>0){
			str="";
			var data= result.data;
			for(var i in data){
				str +='<option value="'+data[i].NAME+'">'+data[i].NAME+'('+data[i].CNT+')</option>';
			}
			$('#hospICDOperDesc').html(str);	
		}else{
			$('#hospICDOperDesc').html(str);
		}	
	});
}
/**
 * @void
 * @ Discription:根据BJ诊断编码获取描述
 * @icdMatch.js
 */
function findBJOperDescByCode(){
	var code=$('#BJICDOperCode').val();
	if(!code) return;
	$.post(contextPath + "/matchIcd/findBJDescByCode.dhc",{"type":"O","code":code,"icdVersion":$("#"+tabId+" #icdVersion").val()}).done(function(result){
		if(result.success && result.data.length>0){
			var data= result.data;
			$('#BJICDOperDesc').val(data[0].NAME);	
		}else{
			$('#BJICDOperDesc').attr("placeholder","请输入正确编码");
		}	
	});
}

